# Google command line interface
# Copyright (C) 2005 by Deryck Hodge
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


import re, os, sys

USERCONF = os.getenv('HOME') + '/.gcli'

defaults = {
    'key' : "",
    'keypath' : "",
    'query' : None,
    'index_start' : 0, 
    'max_results' : 10,
    'filter' : False, 
    'restrictions' : "", 
    'safe_search' : False, 
    'language' : "", 
    'input_enc' : 'utf-8',
    'output_enc' : 'utf-8',
    'display' : 'brief',
    'count' : False,
}

display_opts = ['url', 'title', 'excerpt', 'brief', 'all', 'google']

try:
    CONFIG = open(USERCONF + '/config', 'r').readlines()
except:
    CONFIG = None


def conf_opt_exists(param):
    """ Should only be called by functions that are reading the
        config file.  The calling function should test there 
        actually is a config. """

    conf_opt = False
    commented = re.compile('#(.*)' + param)

    for line in CONFIG:
        if line.find(param) > -1 and not commented.search(line):
            conf_opt = True

    return conf_opt


def get_key():
    try:
        set_param('KEYPATH')
        keypath = defaults['keypath']

        if keypath != "":
            if keypath[-1:] == '/':
                key = open(keypath + 'key', 'r').read() 
            else:
                key = open(keypath + '/key', 'r').read() 
        else:
            key = open(USERCONF + '/key', 'r').read() 

        if re.search('\n', key):
            key = re.sub('\n', '', key)

        defaults['key'] = key

    except:
        print """You must save your Google Web Search developer key at 
%s/key before using gcli or the libgcli modules.""" % USERCONF
        sys.exit(1) 


def set_param(param):
    if CONFIG:
        if conf_opt_exists(param):
            for line in CONFIG:
                if line.find(param) > -1:
                    line = re.sub('\s', '', line)
                    opt, value = line.split('=')
                    if value == 'true' or value == 'True':
                        defaults[param.lower()] = bool(value)
                    elif value == 'false' or value == 'False':
                        defaults[param.lower()] = bool(value)
                    elif param == 'MAX_RESULTS' or param == 'INDEX_START':
                        defaults[param.lower()] = int(value)
                    else:
                        defaults[param.lower()] = value


def load_params():
    get_key()

    for param in defaults:
        if param not in ['key', 'query', 'input_enc', 'output_enc', 'count']:
            set_param(param.upper())


def set_query(query):
    defaults['query'] = query


class Conf:
    def __init__(self):
        """ Load default values. """

        load_params()
        self.key = defaults['key']
        self.query = defaults['query']
        self.index_start = defaults['index_start']
        self.max_results = defaults['max_results']
        self.filter = defaults['filter']
        self.restrictions = defaults['restrictions']
        self.safe_search = defaults['safe_search']
        self.language = defaults['language']
        self.input_enc = defaults['input_enc']
        self.output_enc = defaults['output_enc']
        self.display = defaults['display']
        self.count = defaults['count']


class Params(Conf):

    def __init__(self):
        """ Class for parsing command line arguments. """
        Conf.__init__(self)

    def toggle_filter(self):
        if self.filter == True:
            self.filter = False
        elif self.filter == False:
            self.filter = True

    def toggle_safe(self):
        if self.safe == True:
            self.safe = False
        elif self.safe == False:
            self.safe = True

    def start_at(self, offset):
        self.index_start = offset

    def search_params(self):
        return (self.key, self.query, self.index_start, self.max_results, 
                self.filter, self.restrictions, self.safe_search, self.language,
                self.input_enc, self.output_enc)


# The rest is just unused variables, but these may see
# some work in future versions.
country = {
    'Andorra' : 'countryAD',
    'United Arab Emirates' : 'countryAE',
    'Afghanistan' : 'countryAF',
    'Antigua and Barbuda' : 'countryAG',
    'Anguilla' : 'countryAI',
    'Albania' : 'countryAL',
    'Armenia' : 'countryAM',
    'Netherlands Antilles' : 'countryAN',
    'Angola' : 'countryAO',
    'Antarctica' : 'countryAQ',
    'Argentina' : 'countryAR',
    'American Samoa' : 'countryAS',
    'Austria' : 'countryAT',
    'Australia' : 'countryAU',
    'Aruba' : 'countryAW',
    'Azerbaijan' : 'countryAZ',
    'Bosnia and Herzegowina' : 'countryBA',
    'Barbados' : 'countryBB',
    'Bangladesh' : 'countryBD',
    'Belgium' : 'countryBE',
    'Burkina Faso' : 'countryBF',
    'Bulgaria' : 'countryBG',
    'Bahrain' : 'countryBH',
    'Burundi' : 'countryBI',
    'Benin' : 'countryBJ',
    'Bermuda' : 'countryBM',
    'Brunei Darussalam' : 'countryBN',
    'Bolivia' : 'countryBO',
    'Brazil' : 'countryBR',
    'Bahamas' : 'countryBS',
    'Bhutan' : 'countryBT',
    'Bouvet Island' : 'countryBV',
    'Botswana' : 'countryBW',
    'Belarus' : 'countryBY',
    'Belize' : 'countryBZ',
    'Canada' : 'countryCA',
    'Cocos (Keeling) Islands' : 'countryCC',
    'Congo, The Democratic Republic of the' : 'countryCD',
    'Central African Republic' : 'countryCF',
    'Congo' : 'countryCG',
    'Burundi' : 'countryBI',
    'Benin' : 'countryBJ',
    'Bermuda' : 'countryBM',
    'Brunei Darussalam' : 'countryBN',
    'Bolivia' : 'countryBO',
    'Brazil' : 'countryBR',
    'Bahamas' : 'countryBS',
    'Bhutan' : 'countryBT',
    'Bouvet Island' : 'countryBV',
    'Botswana' : 'countryBW',
    'Belarus' : 'countryBY',
    'Belize' : 'countryBZ',
    'Canada' : 'countryCA',
    'Cocos (Keeling) Islands' : 'countryCC',
    'Congo, The Democratic Republic of the' : 'countryCD',
    'Central African Republic' : 'countryCF',
    'Congo' : 'countryCG',
    'Switzerland' : 'countryCH',
    'Cote D\'ivoire' : 'countryCI',
    'Cook Islands' : 'countryCK',
    'Chile' : 'countryCL',
    'Cameroon ' : 'countryCM',
    'China' : 'countryCN',
    'Colombia' : 'countryCO',
    'Costa Rica' : 'countryCR',
    'Cuba' : 'countryCU',
    'Cape Verde' : 'countryCV',
    'Christmas Island' : 'countryCX',
    'Cyprus' : 'countryCY',
    'Czech Republic' : 'countryCZ',
    'Germany' : 'countryDE',
    'Djibouti' : 'countryDJ',
    'Denmark' : 'countryDK',
    'Dominica' : 'countryDM',
    'Dominican Republic' : 'countryDO',
    'Algeria' : 'countryDZ',
    'Ecuador' : 'countryEC',
    'Estonia' : 'countryEE',
    'Egypt' : 'countryEG',
    'Western Sahara' : 'countryEH',
    'Eritrea' : 'countryER',
    'Spain' : 'countryES',
    'Ethiopia' : 'countryET',
    'European Union' : 'countryEU',
    'Finland' : 'countryFI',
    'Fiji' : 'countryFJ',
    'Falkland Islands (Malvinas)' : 'countryFK',
    'Micronesia, Federated States of' : 'countryFM',
    'Faroe Islands' : 'countryFO',
    'France' : 'countryFR',
    'France, Metropolitan' : 'countryFX',
    'Gabon' : 'countryGA',
    'United Kingdom' : 'countryUK',
    'Grenada' : 'countryGD',
    'Georgia' : 'countryGE',
    'French Quiana' : 'countryGF',
    'Ghana' : 'countryGH',
    'Gibraltar' : 'countryGI',
    'Greenland' : 'countryGL',
    'Gambia' : 'countryGM',
    'Guinea' : 'countryGN',
    'Guadeloupe' : 'countryGP',
    'Equatorial Guinea' : 'countryGQ',
    'Greece' : 'countryGR',
    'South Georgia and the South Sandwich Islands' : 'countryGS',
    'Guatemala' : 'countryGT',
    'Guam' : 'countryGU',
    'Guinea-Bissau' : 'countryGW',
    'Guyana' : 'countryGY',
    'Hong Kong' : 'countryHK',
    'Heard and Mc Donald Islands' : 'countryHM',
    'Honduras' : 'countryHN',
    'Croatia (local name: Hrvatska)' : 'countryHR',
    'Haiti' : 'countryHT',
    'Hungary' : 'countryHU',
    'Indonesia' : 'countryID',
    'Ireland' : 'countryIE',
    'Israel' : 'countryIL',
    'India' : 'countryIN',
    'British Indian Ocean Territory' : 'countryIO',
    'Iraq' : 'countryIQ',
    'Iran (Islamic Republic of)' : 'countryIR',
    'Iceland' : 'countryIS',
    'Italy' : 'countryIT',
    'Jamaica' : 'countryJM',
    'Jordan' : 'countryJO',
    'Japan ' : 'countryJP',
    'Kenya' : 'countryKE',
    'Kyrgyzstan' : 'countryKG',
    'Cambodia' : 'countryKH',
    'Kiribati' : 'countryKI',
    'Comoros' : 'countryKM',
    'Saint Kitts and Nevis' : 'countryKN',
    'Korea, Democratic People\'s Republic of' : 'countryKP',
    'Korea, Republic of' : 'countryKR',
    'Kuwait' : 'countryKW',
    'Cayman Islands' : 'countryKY',
    'Kazakhstan' : 'countryKZ',
    'Lao People\'s Democratic Republic' : 'countryLA',
    'Lebanon' : 'countryLB',
    'Saint Lucia' : 'countryLC',
    'Liechtenstein' : 'countryLI',
    'Sri Lanka' : 'countryLK',
    'Liberia' : 'countryLR',
    'Lesotho' : 'countryLS',
    'Lithuania' : 'countryLT',
    'Luxembourg' : 'countryLU',
    'Latvia' : 'countryLV',
    'Libyan Arab Jamahiriya' : 'countryLY',
    'Morocco' : 'countryMA',
    'Monaco' : 'countryMC',
    'Moldova' : 'countryMD',
    'Madagascar' : 'countryMG',
    'Marshall Islands' : 'countryMH',
    'Macedonia, The Former Yugoslav Republic of' : 'countryMK',
    'Mali' : 'countryML',
    'Myanmar' : 'countryMM',
    'Mongolia' : 'countryMN',
    'Macau' : 'countryMO',
    'Northern Mariana Islands' : 'countryMP',
    'Martinique' : 'countryMQ',
    'Mauritania' : 'countryMR',
    'Montserrat' : 'countryMS',
    'Malta' : 'countryMT',
    'Mauritius' : 'countryMU',
    'Maldives' : 'countryMV',
    'Malawi' : 'countryMW',
    'Mexico' : 'countryMX',
    'Malaysia' : 'countryMY',
    'Mozambique' : 'countryMZ',
    'Namibia' : 'countryNA',
    'New Caledonia' : 'countryNC',
    'Niger' : 'countryNE',
    'Norfolk Island' : 'countryNF',
    'Nigeria' : 'countryNG',
    'Nicaragua' : 'countryNI',
    'Netherlands' : 'countryNL',
    'Norway' : 'countryNO',
    'Nepal' : 'countryNP',
    'Nauru' : 'countryNR',
    'Niue' : 'countryNU',
    'New Zealand' : 'countryNZ',
    'Oman' : 'countryOM',
    'Panama' : 'countryPA',
    'Peru' : 'countryPE',
    'French Polynesia' : 'countryPF',
    'Papua New Guinea' : 'countryPG',
    'Philippines' : 'countryPH',
    'Pakistan' : 'countryPK',
    'Poland' : 'countryPL',
    'St. Pierre and Miquelon' : 'countryPM',
    'Pitcairn' : 'countryPN',
    'Puerto Rico' : 'countryPR',
    'Palestine' : 'countryPS',
    'Portugal ' : 'countryPT',
    'Palau' : 'countryPW',
    'Paraguay' : 'countryPY',
    'Qatar' : 'countryQA',
    'Reunion' : 'countryRE',
    'Romania' : 'countryRO',
    'Russian Federation' : 'countryRU',
    'Rwanda' : 'countryRW',
    'Saudi Arabia' : 'countrySA',
    'Solomon Islands' : 'countrySB',
    'Seychelles' : 'countrySC',
    'Sudan' : 'countrySD',
    'Sweden' : 'countrySE',
    'Singapore' : 'countrySG',
    'St. Helena' : 'countrySH',
    'Slovenia' : 'countrySI',
    'Svalbard and Jan Mayen Islands' : 'countrySJ',
    'Slovakia (Slovak Republic)' : 'countrySK',
    'Sierra Leone' : 'countrySL',
    'San Marino' : 'countrySM',
    'Senegal' : 'countrySN',
    'Somalia' : 'countrySO',
    'Suriname' : 'countrySR',
    'Sao Tome and Principe' : 'countryST',
    'El Salvador' : 'countrySV',
    'Syria' : 'countrySY',
    'Swaziland' : 'countrySZ',
    'Turks and Caicos Islands' : 'countryTC',
    'Chad' : 'countryTD',
    'French Southern Territories' : 'countryTF',
    'Togo' : 'countryTG',
    'Thailand' : 'countryTH',
    'Tajikistan' : 'countryTJ',
    'Tokelau' : 'countryTK',
    'Turkmenistan' : 'countryTM',
    'Tunisia' : 'countryTN',
    'Tonga' : 'countryTO',
    'East Timor' : 'countryTP',
    'Turkey' : 'countryTR',
    'Trinidad and Tobago' : 'countryTT',
    'Tuvalu' : 'countryTV',
    'Taiwan' : 'countryTW',
    'Tanzania' : 'countryTZ',
    'Ukraine' : 'countryUA',
    'Uganda' : 'countryUG',
    'United States Minor Outlying Islands' : 'countryUM',
    'United States' : 'countryUS',
    'Uruguay' : 'countryUY',
    'Uzbekistan' : 'countryUZ',
    'Holy See (Vatican City State)' : 'countryVA',
    'Saint Vincent and the Grenadines' : 'countryVC',
    'Venezuela' : 'countryVE',
    'Virgin Islands (British)' : 'countryVG',
    'Virgin Islands (U.S.)' : 'countryVI',
    'Vietnam' : 'countryVN',
    'Vanuatu' : 'countryVU',
    'Wallis and Futuna Islands' : 'countryWF',
    'Samoa' : 'countryWS',
    'Yemen' : 'countryYE',
    'Mayotte' : 'countryYT',
    'Yugoslavia' : 'countryYU',
    'South Africa' : 'countryZA',
    'Zambia' : 'countryZM',
    'Zaire' : 'countryZR',
}

topic = {
    'US. Government' : 'unclesam',
    'Linux' : 'linux',
    'Macintosh' : 'mac',
    'FreeBSD' : 'bsd',
}

langauges = {
    'Arabic' : 'lang_ar',
    'Chinese (S)' : 'lang_zh-CN',
    'Chinese (T)' : 'lang_zh-TW',
    'Czech' :  'lang_cs',
    'Danish' : 'lang_da',
    'Dutch' :  'lang_nl',
    'English' : 'lang_en',
    'Estonian' : 'lang_et',
    'Finnish' : 'lang_fi',
    'French' : 'lang_fr',
    'German' : 'lang_de',
    'Greek' : 'lang_el',
    'Hebrew' : 'lang_iw',
    'Hungarian' : 'lang_hu',
    'Icelandic' : 'lang_is',
    'Italian' : 'lang_it',
    'Japanese' : 'lang_ja',
    'Korean' : 'lang_ko',
    'Latvian' : 'lang_lv',
    'Lithuanian' : 'lang_lt',
    'Norwegian' : 'lang_no',
    'Portuguese' : 'lang_pt',
    'Polish' : 'lang_pl',
    'Romanian' : 'lang_ro',
    'Russian' : 'lang_ru',
    'Spanish' : 'lang_es',
    'Swedish' : 'lang_sv',
    'Turkish' : 'lang_tr',
}

